import Vue from 'vue'
import VueRouter from 'vue-router'
import store from './../store'
import { Message } from 'element-ui'
const Register = () => import('../views/Register.vue')
const Test = () => import('../views/Test.vue')
const Login = () => import('../views/Login.vue')
const NotFound = () => import('../views/errorPage/404.vue')
const Forbidden = () => import('../views/errorPage/403.vue')
const Layout = () => import('../views/layout/index.vue')
const Home = () => import('../views/home/index.vue')
Vue.use(VueRouter)

// 登录前的路由
const routes = [
  // {
  //   path: '/',
  //   redirect: '/home'
  // },
  {
    path: '/test',
    name: 'test',
    component: Test
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    beforeEnter(to, from, next) {
      if (store.state.token) {
        Message.warning({ message: '已登录', duration: 500 })
        next('/home')
      } else {
        next()
      }
    }
  },
  
]


/* 
根据用户的权限不同，所能看到的页面和可操作性也不同
admin ->所有页面都可以看得到
vip ->属于vip的权限
svip ->更多额vip的权限
后期通过addRouter()来动态添加  
*/
//登录后准备动态加载的路由
export const DynamicRoutes = [
  {
    path: "",
    component: Layout,
    name: 'container',
    meta: {
      requiresAuth: true,
      name: "首页"
    },
    children: [
      {
        path: "home",
        component: Home,
        name: "home",
        meta: {
          //匹配规则
          name: "首页",
          icon: "icon-name"
        }
      }
    ],
  },
  {
    path: "/403",
    component: Forbidden
  },
  {
    path: '*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (!store.state.token) {//未登录 判断页面是否需要登录
    console.log(to);
    if ((to.path == '/login' || to.path == '/register') && !to.matched.some(item => item.meta.requiresAuth)) {
      next()//不需要登录
    } else {
      next('/login')
    }
  } else {// 已登录 处理路由访问权限
    /*
    路由权限的业务
    1.定义好全部的路由地址
    2.通过用户不同像后台请求不同的用户权限数据
    3.对用户权限做对比:请求数据==全部的路由取出来作为路由配置 
    */
    if (!store.state.permission.permissionList) {
      store.dispatch('permission/FETCH_PERMISSION').then(() => {
        console.log(to);
        next({ path: to.path })
      })
    } else {
      if (to.path !== '/login') {
        next()
      } else {
        next(from.fullPath)
      }
    }
  }
})

router.afterEach((to, from, next) => {
  var routerList = to.matched
  console.log(routerList);
  store.commit('setCrumbList', routerList)
  // store.commit('permission/SET_CURRENT_MENU', to.name)
})
export default router
